#!/bin/bash

readonly script_dir="$(dirname "$0")"

# Try to find an hhvm binary. Prefer php (if it's hhvm) or hhvm from $PATH. If
# neither of those work, look for hhvm in a few common locations, preferring a
# released version over a locally-built version for stability.
function get_hhvm_bin {
    local -a candidates
    candidates=(
        "/usr/local/hphpi/bin/hhvm"
        "$script_dir/../../buck-out/gen/hphp/hhvm/hhvm"
        "$script_dir/../hhvm/hhvm"
    )

    if php --version |& grep -qF 'HipHop VM'; then
        command -v php
        return
    fi

    if command -v hhvm 2>/dev/null; then
        return
    fi

    for binary in "${candidates[@]}"; do
        if [[ -x "$binary" ]]; then
            echo "$binary"
            return
        fi
    done

    return 1
}

if ! hhvm_bin="$(get_hhvm_bin)"; then
    echo "Couldn't find hhvm binary to run test/run" 1>&2
    exit 1
fi

exec "$hhvm_bin" "$script_dir/run.php" "$@"
